package com.example.springboot.config.bootcustomize.messageconverter;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/1/25 19:01
 */
public class MyMessageConverter extends AbstractHttpMessageConverter<UserEntity> {
    /**
     * 自定义媒体类型
     * 当请求的消息头我application/czk是会运用此消息转换器
     */
    public MyMessageConverter() {
        super(new MediaType("application", "nzq", StandardCharsets.UTF_8));
    }

    /**
     * 请求时会调用
     *
     * @param aClass
     * @param httpInputMessage
     * @return
     * @throws IOException
     * @throws HttpMessageNotReadableException
     */
    @Override
    protected UserEntity readInternal(Class<? extends UserEntity> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        // 拿到实体对象
        InputStream body = httpInputMessage.getBody();
        // 转换成字符串
        String string = StreamUtils.copyToString(body, StandardCharsets.UTF_8);
        // 根据自己的协议来封装对象，这里切割-来封装对象
        String[] split = string.split("-");
        UserEntity userEntity = new UserEntity();
        userEntity.setName(split[0]);
        userEntity.setAge(Integer.parseInt(split[1]));
        return userEntity;
    }

    /**
     * 写数据
     * 返回数据时会调用此消息转换器进行转换
     *
     * @param userEntity
     * @param httpOutputMessage
     * @throws IOException
     * @throws HttpMessageNotWritableException
     */
    @Override
    protected void writeInternal(UserEntity userEntity, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
        // 拿到实体类
        int age = userEntity.getAge();
        String name = userEntity.getName();
        // 写回浏览器
        String str = "年龄=" + age + "姓名=" + name;
        httpOutputMessage.getBody().write(str.getBytes());
    }

    /**
     * canRead和canWrite方法会调用
     *
     * @param aClass
     * @return
     */
    @Override
    protected boolean supports(Class aClass) {
        // 验证字节码对象
        return UserEntity.class.isAssignableFrom(aClass);
    }
}
